%include "I:\workdata\706727\Build\Directories_And_SampleRestrictions.sas";

/* Basedata */

data base (drop=BEFSourceYear FOED_DAG);
set raw.befv (keep= pnr BEFSourceYear kom FOED_DAG where=(BEFSourceyear>1999 and BEFSourceYear<2015 and BEFSourceyear-year(FOED_DAG)<25 and BEFSourceyear-year(FOED_DAG)>12));
year=befsourceyear;
birthmonth=month(FOED_DAG);
birthyear=year(FOED_DAG);
run;

/* hospital */
data hosp (drop=c_spec);
set psyc.lpsypop2014 (keep= pnr recnum  c_spec) ;
if c_spec="52" then childhosp=1;
if c_spec="50" then childhosp=0;
run;

/* Ambulatory visits */
data amb (drop=d_ambdto where=(year>1999 and year<2015));
set psyc.lpsybes2014 (keep=  recnum d_ambdto) ;
year=year(d_ambdto);
month=month(d_ambdto);
amb=1;
run;

/* Merge */

proc sql;
create table childhosp(drop=recnum) as select * from hosp as a

left join amb as b on a.recnum=b.recnum;
quit;

proc sql;
create table childhosp2 as select * from childhosp as a

left join base as b on a.pnr=b.pnr and a.year=b.year;
quit;

data childhosp2(where=(age ne . and childhosp ne .));
set childhosp2;
if birthmonth<=month and birthmonth ne . then age=floor(year-birthyear +(month-birthmonth)/12);
if birthmonth>month and month ne .       then age=floor(year-birthyear-1+(month-birthmonth+12)/12);
run;

proc sql;
create table childhosp as select * from childhosp2 as a

left join form.newmuni(drop=navn nynavn) as b on a.kom=b.kom;
quit;

/* Old Muni */
proc sort data=childhosp2;
by year kom age;
run;

proc means data=childhosp2 nway noprint;
var childhosp;
by year kom age;
output out=final.ChildhospRegOldMuniInt mean=;
run;

/* New Muni */
data childhosp(drop=nykom);
set childhosp;
if year<2007 then kom=nykom;
run;

proc sort data=childhosp;
by year kom age;
run;

proc means data=childhosp nway noprint;
var childhosp;
by year kom age;
output out=final.ChildhospRegNewMuniInt mean=;
run;
